package com.smt.take.utils

import cn.jpush.android.api.JPushInterface
import com.mob.MobApplication
import com.mob.MobSDK
import com.smt.take.model.beans.CacheSelectedInfo
import com.smt.take.model.beans.UserBean
import java.util.concurrent.CopyOnWriteArrayList


class TakeOutApp : MobApplication() {

    // 点餐缓存集合 CopyOnWriteArrayList是线程安全的集合
    val infos: CopyOnWriteArrayList<CacheSelectedInfo> = CopyOnWriteArrayList()

    fun queryCacheSelectedInfoByGoodsId(goodsId: Int): Int {
        var count = 0
        for (i in infos.indices) {
            val info = infos[i]
            if (info.goodsId == goodsId) {
                count = info.count
                break
            }
        }
        return count
    }

    fun queryCacheSelectedInfoByTypeId(typeId: Int): Int {
        var count = 0
        for (i in infos.indices) {
            val info = infos[i]
            if (info.typeId == typeId) {
                count += info.count
            }
        }
        return count
    }

    fun queryCacheSelectedInfoBySellerId(sellerId: Int): Int {
        var count = 0
        for (i in infos.indices) {
            val info = infos[i]
            if (info.sellerId == sellerId) {
                count += info.count
            }
        }
        return count
    }

    fun addCacheSelectedInfo(info: CacheSelectedInfo?) {
        infos.add(info)
    }

    fun clearCacheSelectedInfo(sellerId: Int) {
        val temp = ArrayList<CacheSelectedInfo>()
        for (i in infos.indices) {
            val info = infos[i]
            if (info.sellerId == sellerId) {
                //infos.remove(info)
                temp.add(info)
            }
            infos.removeAll(temp)
        }
    }

    fun deleteCacheSelectedInfo(goodsId: Int) {
        for (i in infos.indices) {
            val info = infos[i]
            if (info.goodsId == goodsId) {
                infos.remove(info)
                break
            }
        }
    }

    fun updateCacheSelectedInfo(goodsId: Int, operation: Int) {
        for (i in infos.indices) {
            val info = infos[i]
            if (info.goodsId == goodsId) {
                when (operation) {
                    Constants.ADD -> info.count = info.count + 1
                    Constants.MINUS -> info.count = info.count - 1
                }
            }
        }
    }

    companion object {
        var sUser: UserBean = UserBean()
        lateinit var instance: TakeOutApp
    }

    // 应用程序的入口
    override fun onCreate() {
        super.onCreate()
        instance = this
        MobSDK.submitPolicyGrantResult(false, null)
        sUser.id = -1 //未登录用户id=-1
        JPushInterface.setDebugMode(true)
        JPushInterface.init(this)
    }
}